<?php

class Socket {
    private $socket;
    
    public function __construct($socket) {
        $this->socket = $socket;
    }
    
    public function write_read($txt) {
        $output = $this->write($txt);
        return $output['success'] ? $this->read() : $output;
    }

    public function read() {
        $output = '';
        do {
            $buf = socket_read($this->socket, 4096, PHP_BINARY_READ);
            if (false === $buf) {
                return array( 
                    'success' => false,
                    'message' => "socket_read() failed: reason: " . socket_strerror(socket_last_error($this->socket)) . "\n"
                );
            }
            if (strpos($buf,"\n") !== false) {
                $output .= rtrim($buf);
                break;
            }
            $output .= $buf;
        } while ($buf !== '');
        return array(
            'success' => true,
            'payload' => $output
        );
    }
    
    public function write($txt) {
        $txt .= "\n";
        while (true) {
            $size = strlen($txt);
            if (($written_size = socket_write($this->socket,$txt,$size)) === false) {
                return array( 
                    'success' => false,
                    'message' => "socket_write() failed: reason: " . socket_strerror(socket_last_error($this->socket)) . "\n"
                );
            }
            if ($written_size < $size) $txt = substr($txt,$written_size);
            else return array('success'=>true);
        }
    }
}

        

?>